package design.pattern.Lu06ProxyPattern;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program JavaBase
 * @description: 动态代理，再次封装
 * @author: zhanglu
 * @create: 2020-03-29 16:25:00
 */
public class Lu06ProxyPattern04 {

    public static void main(String[] args) {

        IGamePlayer04 iGamePlayer04 = new GamePlayer04("张三");

//        InvocationHandler h = new GamePlayerProxy04(iGamePlayer04);
//
//        IGamePlayer04 player04 = DynamicProxy.newProxyInstance(iGamePlayer04.getClass().getClassLoader(), iGamePlayer04.getClass().getInterfaces(), h);

        IGamePlayer04 player04  = SubjectDynamicProxy.t(iGamePlayer04);

        player04.login("zhangsan", "111111");


    }

}


interface IGamePlayer04{

    void login(String username, String password);

    void killBoss();

    void upgrade();

}

class GamePlayer04 implements IGamePlayer04{

    private String name;

    public GamePlayer04(String name){
        this.name = name;
    }

    @Override
    public void login(String username, String password) {
        System.out.println("登陆：" + this.name + " - " + username + " - " + password);
    }

    @Override
    public void killBoss() {
        System.out.println("杀怪：" + this.name);
    }

    @Override
    public void upgrade() {
        System.out.println("升级：" + this.name);
    }
}

class GamePlayerProxy04 implements InvocationHandler{

    private Object object;

    public GamePlayerProxy04(Object object){
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Object invoke = method.invoke(this.object, args);

        return invoke;
    }

}

class DynamicProxy{

    protected static <T> T newProxyInstance(ClassLoader loader,
                                            Class<?>[] interfaces,
                                            InvocationHandler h){
        T t = (T) Proxy.newProxyInstance(loader, interfaces, h);
        return t;
    }

}

class SubjectDynamicProxy extends DynamicProxy{

    public static <T> T t(IGamePlayer04 iGamePlayer04){

        InvocationHandler h = new GamePlayerProxy04(iGamePlayer04);

        return newProxyInstance(iGamePlayer04.getClass().getClassLoader(), iGamePlayer04.getClass().getInterfaces(), h);

    }

}

